package fragments;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import adapters.CountSpinnerAdapter;
import beans.NewUserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.DigitalTrans;
import utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class FactorySetFragment extends BaseFragment {
    @BindView(R.id.spinner_factoryset_fragment_exit)
    Spinner spinnerExit;
    @BindView(R.id.ll_factoryset_fragment_exit)
    LinearLayout llExit;
    Unbinder unbinder;
    @BindView(R.id.et_factoryset_fragment_sound)
    EditText etSound;
    private Spinner spinnerLockScreen, spinnerCabinetNumber;
    //    private Spinner spinnerPower;
//    private Spinner spinnerTime;
    private String[] content = {"30s", "60s", "120s", "180s"};
    private String[] cabinetNumber = {"1", "2", "3", "4", "5"};
    private String[] exit = {"3h", "6h", "8h", "12h", "24h"};
    private String powerSet, timeSet;
    private int lockScreenTime;
    private NewUserInfoBean.DataBean userInfoBean;
    private int roleInfoId = 5;

    private CountSpinnerAdapter adapter, cabinetAdapter, exitAdapter;

    private CheckBox cbOne, cbTwo, cbThree, cbFour;
    private View view;
    private MyHandler allHandler;
    private int selectCabinetCode = 1, beforeSelect = 1;

    private EditText etPower, etTime;
    //用于拼接
    private StringBuilder sbSet = new StringBuilder();
    private LinearLayout llFactoryAuthFirst, llFactoryAuthSecond, llFactoryAuthThird, llFactoryAuthFourth;

    private SharedPreferences sharedPreferences;
    private Button bt_sure;
    private Context mContext;
    private String antenna;
    private int mPosition;
    private boolean isVisible = false;
    private SharedPreferences.Editor edit;
    private int maxPower = 3150;
    private int minPower = 500;
    private int type = 4;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        view = setContentView(R.layout.fragment_factory_set);
        view = inflater.inflate(R.layout.fragment_factory_set, null);
        mContext = getContext();
        unbinder = ButterKnife.bind(this, view);

        initFragmentView(view);

        // 账号注销 协和显示
        if (Constants.IS_FUYI) {
            llExit.setVisibility(View.GONE);
        } else {
            llExit.setVisibility(View.VISIBLE);
        }

        return view;
    }

    //    @Override
    public void initFragmentView(View contentView) {
        sharedPreferences = ActivityUtil.getSharedPreferences(mContext);
        edit = sharedPreferences.edit();
        antenna = sharedPreferences.getString(Constants.ANTENNA, "");

        spinnerLockScreen = (Spinner) contentView.findViewById(R.id.spinner_factoryset_fragment_lockscreen);
        spinnerCabinetNumber = (Spinner) contentView.findViewById(R.id.spinner_factoryset_fragment_cabinet);
//
        cabinetAdapter = new CountSpinnerAdapter(mContext, R.layout.factory_set_spinner, cabinetNumber);
        adapter = new CountSpinnerAdapter(getContext(), R.layout.factory_set_spinner, content);
        exitAdapter = new CountSpinnerAdapter(getContext(), R.layout.factory_set_spinner, exit);

        spinnerCabinetNumber.setAdapter(cabinetAdapter);
        spinnerLockScreen.setAdapter(adapter);
        spinnerExit.setAdapter(exitAdapter);
//
        cbOne = (CheckBox) contentView.findViewById(R.id.cb_factory_set_fragment_one);
        cbTwo = (CheckBox) contentView.findViewById(R.id.cb_factory_set_fragment_two);
        cbThree = (CheckBox) contentView.findViewById(R.id.cb_factory_set_fragment_three);
        cbFour = (CheckBox) contentView.findViewById(R.id.cb_factory_set_fragment_four);

        bt_sure = (Button) contentView.findViewById(R.id.bt_factoryset_fragment_finish);

        llFactoryAuthFirst = (LinearLayout) contentView.findViewById(R.id.ll_factory_auth_first);
        llFactoryAuthSecond = (LinearLayout) contentView.findViewById(R.id.ll_factory_auth_second);
        llFactoryAuthThird = (LinearLayout) contentView.findViewById(R.id.ll_factory_auth_third);
        llFactoryAuthFourth = (LinearLayout) contentView.findViewById(R.id.ll_factory_auth_fourth);

        etPower = (EditText) contentView.findViewById(R.id.et_factoryset_fragment_power);
        etTime = (EditText) contentView.findViewById(R.id.et_factoryset_fragment_time);

        allHandler = SingletonClass.getSingleton(MyHandler.class);

        if (isVisible) {
            getCabinetSet();
        }
        Log.e("EEE", "initFragmentView: " + Constants.TIME_OUT);
        int timeout_key = sharedPreferences.getInt(Constants.SELECT_TIME_OUT_KEY, 1);
        int exit_key = sharedPreferences.getInt(Constants.SELECT_EXIT_KEY, 2);
        spinnerLockScreen.setSelection(timeout_key);
        spinnerExit.setSelection(exit_key);

        int anInt = sharedPreferences.getInt(Constants.SOUND_KEY, 50);
        etSound.setText(anInt + "");
    }

    private void getCabinetSet() {
        Message message = allHandler.obtainMessage();
        message.what = HandlerConstant.GET_CABINET_SET;
        message.obj = selectCabinetCode;
        allHandler.sendMessage(message);
    }

    @Override
    public void setListener() {

        bt_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = etSound.getText().toString();
                if (!TextUtils.isEmpty(s)) {
                    edit.putInt(Constants.SOUND_KEY, Integer.parseInt(s));
                    edit.commit();
                }
                sendSetString(sbSet);
            }
        });

        spinnerExit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mPosition = position;
                exitAdapter.setSelectPosition(mPosition);

                if (position != 0) {
                    edit.putInt(Constants.EXIT_KEY, Integer.parseInt(exit[position].substring(0, exit[position].length() - 1)) * 60 * 60 * 1000);
                    edit.putInt(Constants.SELECT_EXIT_KEY, position);
                    edit.commit();
                    Constants.EXIT = Integer.parseInt(exit[position].substring(0, exit[position].length() - 1)) * 60 * 60 * 1000;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerCabinetNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                resetData();
                mPosition = position;
                cabinetAdapter.setSelectPosition(mPosition);

                selectCabinetCode = Integer.parseInt(cabinetNumber[position]);

                Message message = allHandler.obtainMessage();
                message.obj = selectCabinetCode;
                message.what = HandlerConstant.GET_CABINET_SET;
                allHandler.sendMessageDelayed(message, 50);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerLockScreen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                ToastUtil.showToast(TimeOutActivity.this,position+"");
                mPosition = position;
                adapter.setSelectPosition(mPosition);

                if (position != 0) {
                    edit.putInt(Constants.TIME_OUT_KEY, Integer.parseInt(content[position].substring(0, content[position].length() - 1)) * 1000);
                    edit.putInt(Constants.SELECT_TIME_OUT_KEY, position);
                    edit.commit();
                    Constants.TIME_OUT = Integer.parseInt(content[position].substring(0, content[position].length() - 1)) * 1000;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        cbOne.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (type == 1) {
                    cbTwo.setChecked(false);
                    cbThree.setChecked(false);
                    cbFour.setChecked(false);
                    if (isChecked) {
                        cbOne.setEnabled(false);
                    }
                }
            }
        });
    }

    private void sendSetString(StringBuilder sbSet) {
        sbSet.delete(0, sbSet.length());
        if (type == 4) {
            if (cbOne.isChecked()) {
                sbSet.append("01");
            } else {
                sbSet.append("00");
            }
            if (cbTwo.isChecked()) {
                sbSet.append("01");
            } else {
                sbSet.append("00");
            }
            if (cbThree.isChecked()) {
                sbSet.append("01");
            } else {
                sbSet.append("00");
            }
            if (cbFour.isChecked()) {
                sbSet.append("01");
            } else {
                sbSet.append("00");
            }
        } else if (type == 1) {
            sbSet.append("10000000");
        }

        //设置频率
        String power = etPower.getText().toString();
//        if (!TextUtils.isEmpty(power)) {
        if (!TextUtils.isEmpty(power) && minPower < Integer.parseInt(power) && Integer.parseInt(power) <= maxPower) {
            sbSet.append(DigitalTrans.binaryToHex(power, 4));

            //国家频段设置,暂时忽略,FF代表不设置
            sbSet.append("FF");
            //设置时间
            String time = etTime.getText().toString();
//                if (!TextUtils.isEmpty(time)) {
            if (!TextUtils.isEmpty(time) && 0 < Integer.parseInt(time) && Integer.parseInt(time) <= 60) {
                sbSet.append(DigitalTrans.binaryToHex(time, 2));
                Message message = allHandler.obtainMessage();
                message.what = HandlerConstant.SET_RFID;
                message.obj = sbSet.toString();
                allHandler.sendMessage(message);
            } else {
                ToastUtil.showToast(getContext(), "时间的值必须在 0s 至 60s 之间");
            }
        } else {
            ToastUtil.showToast(mContext, "功率的值必须在" + minPower + "至" + maxPower + "之间");
        }
    }

    private void resetData() {
        cbOne.setChecked(false);
        cbTwo.setChecked(false);
        cbThree.setChecked(false);
        cbFour.setChecked(false);
        etPower.setText("");
        etTime.setText("");
    }

    @Override
    protected void onHandleMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.GET_CABINET_SET_SUCCESS:
                SharedPreferences.Editor edit = sharedPreferences.edit();
                String s = (String) msg.obj;
                edit.putString(Constants.ANTENNA, s);
                edit.commit();
                Log.e("aaa", s);

                //功率的设置
                String power = String.valueOf(Integer.parseInt(s.substring(8, 12), 16));
                etPower.setText(power);
                etPower.setSelection(power.length());
                //国家频段设置
                String substring = s.substring(12, 14);
                //时间设置
                String time = String.valueOf(Integer.parseInt(s.substring(14, 16), 16));
                etTime.setText(time);
                etTime.setSelection(time.length());
//  58 4C 4B 4A 01 01 01 12 34 56 78 90 AB 01 18 01 08 25 09 50 00 0D 10 10 10 10 09 C4 01 03 18 0C 4E 01 F4
//  58 4C 4B 4A 01 01 01 01 23 45 67 89 AB AA BB CC DD EE FF 50 00 08 00 01 00 01 07 D0 01 05
//                                                           50 00 0D 00 01 00 01 0B B8 01 04 00 FF FF FF FF
//                584C4B4A0101011234567890AB012233445566     50 00 0D 00 01 00 01 0B B8 01 04 00 0C 4E 01 F4
//                                                           50 00 0D 10 10 10 10 EF 86 D9 03 00 0C 4E 01 F4
//                                                           50 00 0D 00 01 00 01 0A 8C 01 03 30 0A 8C 00 00 3C66
//                if (s.length() > 16) {
//
////                 18 四通道  30 单通道
//                    String singleOrDouble = s.substring(16, 18);
//                    ToastUtil.showToastlog(mContext, singleOrDouble);
//                    if (singleOrDouble.equals("18")) {
//                        type = 4;
//                    } else if (singleOrDouble.equals("30")) {
//                        type = 1;
//                    } else {
//                        type = 4;
//                    }
//
////                 最大功率
//                    maxPower = Integer.parseInt(s.substring(18, 22), 16);
////                 最小功率
//                    minPower = Integer.parseInt(s.substring(22, 26), 16);
//                }
                // 天线设置
                setAntenna(s);
                break;
            case HandlerConstant.SET_CABINET_SUCCESS:
                ToastUtil.showToast(getContext(), "设置成功");
                break;
        }
    }

    private void setAntenna(String s) {
        if (type == 4) {
            //天线的设置
            if (s.substring(0, 2).equals("01")) {
                cbOne.setChecked(true);
            } else {
                cbOne.setChecked(false);
            }
            if (s.substring(2, 4).equals("01")) {
                cbTwo.setChecked(true);
            } else {
                cbTwo.setChecked(false);
            }
            if (s.substring(4, 6).equals("01")) {
                cbThree.setChecked(true);
            } else {
                cbThree.setChecked(false);
            }
            if (s.substring(6, 8).equals("01")) {
                cbFour.setChecked(true);
            } else {
                cbFour.setChecked(false);
            }
        } else if (type == 1) {
            cbOne.setChecked(true);
            cbTwo.setChecked(false);
            cbThree.setChecked(false);
            cbFour.setChecked(false);


            cbOne.setEnabled(false);
            cbTwo.setEnabled(false);
            cbThree.setEnabled(false);
            cbFour.setEnabled(false);
        }

    }

    @Override
    public void onVisiable() {
        super.onVisiable();
        isVisible = true;
    }

    @Override
    public void onUnVisiable() {
        super.onUnVisiable();
        isVisible = false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
